<template>
    <div class="excel-like-page">
        <h1>Excel-like Table Editor</h1>

        <div class="excel-container">
            <div class="excel-toolbar">
                <el-button-group>
                    <el-button :icon="CopyDocument" @click="copyCell"></el-button>
                    <el-button :icon="DocumentCopy" @click="pasteCell"></el-button>
                </el-button-group>
                <el-button-group style="margin-left: 10px;">
                    <el-button :icon="Delete" @click="clearCell"></el-button>
                </el-button-group>
                <el-button type="primary" style="margin-left: 20px;" @click="addRow">Add Row</el-button>
                <el-button type="primary" @click="addColumn">Add Column</el-button>
            </div>

            <div class="excel-table-container" ref="tableContainer" tabindex="0" @keydown.delete="handleDeleteKey"
                @keydown="handleGlobalKeydown">
                <table class="excel-table" ref="excelTable">
                    <thead>
                        <tr>
                            <th class="header-cell corner-cell" :style="{ width: rowHeaderWidth }"></th>
                            <th v-for="(col, index) in columns" :key="index" class="header-cell"
                                :style="{ width: col.width }">
                                {{ col.label }}
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(row, rowIndex) in tableData" :key="rowIndex">
                            <td class="header-cell" :style="{ width: rowHeaderWidth }">{{ rowIndex + 1 }}</td>
                            <td v-for="(col, colIndex) in columns" :key="colIndex"
                                :class="getCellClass(rowIndex, colIndex)" @click="selectCell(rowIndex, colIndex)"
                                @dblclick="startEdit(rowIndex, colIndex)" :style="{ width: col.width }">
                        <!---                     
                <el-input
                  v-if="isEditing(rowIndex, colIndex)"
                  v-model="editValue"
                  :ref="el => setEditInputRef(el, rowIndex, colIndex)"
                  @blur="finishEdit(rowIndex, colIndex)"
                  @keydown.enter="finishEdit(rowIndex, colIndex)"
                  @keydown.tab="handleTabKey($event, rowIndex, colIndex)"
                  @keydown.esc="cancelEdit"
                  @keydown.up="handleArrowKey($event, rowIndex, colIndex, 'up')"
                  @keydown.down="handleArrowKey($event, rowIndex, colIndex, 'down')"
                  @keydown.left="handleArrowKey($event, rowIndex, colIndex, 'left')"
                  @keydown.right="handleArrowKey($event, rowIndex, colIndex, 'right')"
                  class="cell-input"
                  size="small"
                />
                 -->
                               <!---
                                <input-cell-test v-if="isEditing(rowIndex, colIndex)" :model-value="editValue"
                                    @update:model-value="value => { editValue = value }"
                                    :ref="el => setEditInputRef(el, rowIndex, colIndex)"
                                    @blur="finishEdit(rowIndex, colIndex)"
                                    @keydown.enter="finishEdit(rowIndex, colIndex)"
                                    @keydown.tab="handleTabKey($event, rowIndex, colIndex)" @keydown.esc="cancelEdit"
                                    @keydown.up="handleArrowKey($event, rowIndex, colIndex, 'up')"
                                    @keydown.down="handleArrowKey($event, rowIndex, colIndex, 'down')"
                                    @keydown.left="handleArrowKey($event, rowIndex, colIndex, 'left')"
                                    @keydown.right="handleArrowKey($event, rowIndex, colIndex, 'right')"
                                    class="cell-input" :readonly="false" :background-color="'#e6f7ff'" :border="'none'"
                                    :padding="'0px'" :text-align="'left'" />
                                    -->
                                    
                                    
                                    <input-cell v-if="isEditing(rowIndex, colIndex)" 
                                    :number-mode="true"
                                    :model-value="editValue"
                                    @update:model-value="value => { editValue = value }"
                                    :ref="el => setEditInputRef(el, rowIndex, colIndex)"
                                    @blur="finishEdit(rowIndex, colIndex)"
                                    @keydown.enter="finishEdit(rowIndex, colIndex)"
                                    @keydown.tab="handleTabKey($event, rowIndex, colIndex)" @keydown.esc="cancelEdit"
                                    @keydown.up="handleArrowKey($event, rowIndex, colIndex, 'up')"
                                    @keydown.down="handleArrowKey($event, rowIndex, colIndex, 'down')"
                                    @keydown.left="handleArrowKey($event, rowIndex, colIndex, 'left')"
                                    @keydown.right="handleArrowKey($event, rowIndex, colIndex, 'right')"
                                    class="cell-input" :readonly="false" :background-color="'#e6f7ff'" :border="'none'"
                                    :padding="'0px'" :text-align="'left'" 
                                    :no-border="true"
                                    />
                                    

                                <!--- 
                                                    <input
                  v-if="isEditing(rowIndex, colIndex)"
                  v-model="editValue"
                  :ref="el => setEditInputRef(el, rowIndex, colIndex)"
                  @blur="finishEdit(rowIndex, colIndex)"
                  @keydown.enter="finishEdit(rowIndex, colIndex)"
                  @keydown.tab="handleTabKey($event, rowIndex, colIndex)"
                  @keydown.esc="cancelEdit"
                  @keydown.up="handleArrowKey($event, rowIndex, colIndex, 'up')"
                  @keydown.down="handleArrowKey($event, rowIndex, colIndex, 'down')"
                  @keydown.left="handleArrowKey($event, rowIndex, colIndex, 'left')"
                  @keydown.right="handleArrowKey($event, rowIndex, colIndex, 'right')"
                  class="cell-input"
                />
                                    
                                    -->

                                    

                                <span v-else>{{ row[col.prop] }}</span>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <div class="excel-status-bar">
                <span v-if="selectedCell">Cell: {{ getCellAddress() }}</span>
                <span v-else>Select a cell</span>
            </div>
        </div>
    </div>
</template>

<script>
import { CopyDocument, DocumentCopy, Delete } from '@element-plus/icons-vue'
import { ElInput } from 'element-plus'
import InputCellTest from '@/public/views/componentsWeb/InputCellTest.vue'
import InputCell from '../../public/views/componentsWeb/InputCell.vue'

export default {
    name: 'ExcelTestPage',
    components: {
        ElInput,
        InputCellTest,
        InputCell
    },
    setup() {
        return {
            CopyDocument,
            DocumentCopy,
            Delete
        }
    },
    data() {
        return {
            rowHeaderWidth: '60px', // Width for row header column
            columns: [
                { label: 'A', prop: 'colA', width: '100px' },
                { label: 'B', prop: 'colB', width: '100px' },
                { label: 'C', prop: 'colC', width: '100px' },
                { label: 'D', prop: 'colD', width: '100px' },
                { label: 'E', prop: 'colE', width: '100px' },
                { label: 'F', prop: 'colF', width: '100px' },
                { label: 'G', prop: 'colG', width: '100px' },
                { label: 'H', prop: 'colH', width: '100px' },
                { label: 'I', prop: 'colI', width: '100px' },
                { label: 'J', prop: 'colJ', width: '100px' },
                { label: 'K', prop: 'colK', width: '100px' }
            ],
            tableData: [
                { colA: '', colB: '', colC: '', colD: '', colE: '', colF: '', colG: '', colH: '', colI: '', colJ: '', colK: '' },
                { colA: '', colB: '', colC: '', colD: '', colE: '', colF: '', colG: '', colH: '', colI: '', colJ: '', colK: '' },
                { colA: '', colB: '', colC: '', colD: '', colE: '', colF: '', colG: '', colH: '', colI: '', colJ: '', colK: '' },
                { colA: '', colB: '', colC: '', colD: '', colE: '', colF: '', colG: '', colH: '', colI: '', colJ: '', colK: '' },
                { colA: '', colB: '', colC: '', colD: '', colE: '', colF: '', colG: '', colH: '', colI: '', colJ: '', colK: '' }
            ],
            selectedCell: null,
            editingCell: null,
            editValue: '',
            clipboard: null,
            editInput: null,
            typingMode: false
        }
    },
    methods: {
        getCellClass(rowIndex, colIndex) {
            let classes = 'data-cell'

            if (this.selectedCell &&
                this.selectedCell.row === rowIndex &&
                this.selectedCell.col === colIndex) {
                classes += ' selected'
            }

            return classes
        },

        selectCell(rowIndex, colIndex) {
            this.selectedCell = { row: rowIndex, col: colIndex }
            this.typingMode = false
        },

        isEditing(rowIndex, colIndex) {
            return this.editingCell &&
                this.editingCell.row === rowIndex &&
                this.editingCell.col === colIndex
        },

        setEditInputRef(el, rowIndex, colIndex) {
            // Only set the ref when this is the currently editing cell
            if (this.isEditing(rowIndex, colIndex) && el) {
                this.editInput = el
            }
        },

        startEdit(rowIndex, colIndex, initialValue = null) {
            this.selectedCell = { row: rowIndex, col: colIndex }
            this.editingCell = { row: rowIndex, col: colIndex }
            const prop = this.columns[colIndex].prop

            // If initialValue is provided (typing mode), use it
            // Otherwise, use existing cell content
            if (initialValue !== null) {
                this.editValue = initialValue
                this.tableData[rowIndex][prop] = initialValue
            } else {
                // For double-click editing, use existing content
                this.editValue = this.tableData[rowIndex][prop]
            }

            this.editInput = null // Reset the ref
            this.$nextTick(() => {
                // Focus the input element
                if (this.editInput && this.editInput.focus) {
                    this.editInput.focus()
                    // Select all text when double-clicking to edit
                    if (initialValue === null && this.editInput.input) {
                        //  this.editInput.input.select()
                    }
                }
            })
        },

        finishEdit(rowIndex, colIndex) {
            const prop = this.columns[colIndex].prop
            this.tableData[rowIndex][prop] = this.editValue
            this.editingCell = null
            this.selectedCell = { row: rowIndex, col: colIndex }
            this.typingMode = false
        },

        cancelEdit() {
            this.editingCell = null
            this.typingMode = false
        },

        handleTabKey(event, rowIndex, colIndex) {
            event.preventDefault()
            this.finishEdit(rowIndex, colIndex)

            let newCol = (colIndex + 1) % this.columns.length
            let newRow = rowIndex
            if (newCol === 0) {
                newRow = (rowIndex + 1) % this.tableData.length
            }

            this.$nextTick(() => {
                this.startEdit(newRow, newCol)
            })
        },

        handleArrowKey(event, rowIndex, colIndex, direction) {
            event.preventDefault()
            this.finishEdit(rowIndex, colIndex)

            let newRow = rowIndex
            let newCol = colIndex

            switch (direction) {
                case 'up':
                    newRow = Math.max(rowIndex - 1, 0)
                    break
                case 'down':
                    newRow = Math.min(rowIndex + 1, this.tableData.length - 1)
                    break
                case 'left':
                    newCol = Math.max(colIndex - 1, 0)
                    break
                case 'right':
                    newCol = Math.min(colIndex + 1, this.columns.length - 1)
                    break
            }

            this.$nextTick(() => {
                this.startEdit(newRow, newCol)
            })
        },

        handleDeleteKey(event) {
            if (this.selectedCell && !this.editingCell) {
                event.preventDefault()
                this.clearCell()
            }
        },

        handleGlobalKeydown(event) {
            // Handle typing when a cell is selected but not in edit mode
            if (this.selectedCell && !this.editingCell &&
                !this.typingMode &&
                event.key.length === 1 &&
                !event.ctrlKey &&
                !event.metaKey) {
                // Start typing mode - begin editing with the typed character
                this.typingMode = true
                const { row, col } = this.selectedCell
                this.startEdit(row, col, event.key)
                event.preventDefault()
            }
        },

        getCellAddress() {
            if (!this.selectedCell) return ''
            const { row, col } = this.selectedCell
            return `${this.columns[col].label}${row + 1}`
        },

        copyCell() {
            if (!this.selectedCell) return
            const { row, col } = this.selectedCell
            const prop = this.columns[col].prop
            this.clipboard = this.tableData[row][prop]
        },

        pasteCell() {
            if (!this.selectedCell || this.clipboard === null) return
            const { row, col } = this.selectedCell
            const prop = this.columns[col].prop
            this.tableData[row][prop] = this.clipboard
        },

        clearCell() {
            if (!this.selectedCell) return
            const { row, col } = this.selectedCell
            const prop = this.columns[col].prop
            this.tableData[row][prop] = ''
        },

        addRow() {
            const newRow = {}
            this.columns.forEach(col => {
                newRow[col.prop] = ''
            })
            this.tableData.push(newRow)
        },

        addColumn() {
            const nextLetter = String.fromCharCode(65 + this.columns.length)
            this.columns.push({
                label: nextLetter,
                prop: `col${nextLetter}`,
                width: '100px'  // Add default width for new columns
            })

            // Add new property to all rows
            this.tableData.forEach(row => {
                row[`col${nextLetter}`] = ''
            })
        }
    }
}
</script>

<style scoped>
.excel-like-page {
    padding: 20px;
    background-color: #f5f7fa;
    min-height: 100vh;
}

.excel-like-page h1 {
    color: #409eff;
    text-align: center;
    margin-bottom: 20px;
}

.excel-container {
    background: white;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    overflow: hidden;
    display: inline-block;
    /* 让容器根据内容自适应宽度 */
    max-width: 100%;
    /* 但不超过父容器 */
}

.excel-toolbar {
    padding: 10px;
    border-bottom: 1px solid #dcdfe6;
    background-color: #f5f7fa;
}

.excel-table-container {
    overflow: auto;
    max-height: 70vh;
    outline: none;
    /* Remove focus outline */
}

.excel-table {
    border-collapse: collapse;
    table-layout: auto;
    width: auto;
    display: block;
    /* 让表格根据内容自适应宽度 */
}

.excel-table th,
.excel-table td {
    border: 1px solid #dcdfe6;
    padding: 0;
    text-align: center;
    vertical-align: middle;
    height: 30px;
    position: relative;
    white-space: nowrap;
}

.excel-table .header-cell {
    background-color: #f5f7fa;
    font-weight: bold;
    user-select: none;
}

.excel-table .corner-cell {
    width: 40px;
}

.excel-table .data-cell {
    padding: 0px;
    cursor: cell;
    position: relative;
}

.excel-table .data-cell:hover {
    background-color: #f5f7fa;
}

.excel-table .data-cell.selected {
    border: 2px solid #409eff !important;
    z-index: 10;
}

.cell-input {
    width: 100%;
    height: 100%;
}

.cell-input :deep(.el-input__wrapper) {
    box-shadow: none;
    border: none;
    padding: 0 4px;
    height: 100%;
    background-color: #e6f7ff;
}

.excel-status-bar {
    padding: 8px 12px;
    border-top: 1px solid #dcdfe6;
    background-color: #f5f7fa;
    font-size: 14px;
    color: #606266;
}

:deep(.el-button-group .el-button) {
    border-radius: 0;
}

:deep(.el-button-group .el-button:first-child) {
    border-top-left-radius: 4px;
    border-bottom-left-radius: 4px;
}

:deep(.el-button-group .el-button:last-child) {
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
}
</style>